<template>
	<div class="case_data">
		<head-back-title title="案例详情"></head-back-title>
		<el-card>
			<el-form :model="caseForm" ref="caseForm" :rules="caseFormRules" label-width="120px">
				<el-row>
					<div class="title">案例基本信息</div>
					<el-col :span="6">
						<el-form-item label="案例名称:" prop="case_name">
							<el-input :disabled="disabled" v-model="caseForm.case_name" placeholder="请输入案例名称"></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item label="风格:" prop="style_id">
							<el-select :disabled="disabled" v-model="caseForm.style_id" placeholder="请选择风格">
								<el-option v-for="item in styleList" :key="item.style_id" :label="item.style_name" :value="item.style_id"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item label="平方数:" prop="square">
							<el-input :disabled="disabled" v-model="caseForm.square" placeholder="请输入平方数"></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item label="空间类型:" prop="space">
							<el-select :disabled="disabled" v-model="caseForm.space" placeholder="请选择空间类型">
								<el-option v-for="item in apace_list" :key="item" :label="item" :value="item"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item label="序号:" prop="sort">
							<el-input :disabled="disabled" v-model="caseForm.sort" placeholder="请输入序号"></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="20">
						<el-form-item label="商品编号:" prop="goods_sn">
							<el-input rows="3" type="textarea" :disabled="disabled" v-model="goods_sn" placeholder="请输入商品编号,多个编号用“,”隔开"></el-input>
							<span style="cursor: pointer;color: #34a1e0;" @click="openGoodsView">点这里快速选择商品</span>
						</el-form-item>
					</el-col>
					<el-col :span="24"></el-col>
					<el-col :span="12">
						<el-form-item label="简介:">
							<el-input :disabled="disabled" type="textarea" v-model="caseForm.brief" rows="3"></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="24">
						<div class="title">案例图片&视频上传 <el-tag>图片仅限JPG/PNG格式，视频仅限MP4/AVI格式</el-tag>
						</div>
					</el-col>
					<div class="clearfix"></div>
					<div class="case_upload clearfix">
						<el-col :span="6">
							<el-form-item label="上传主图:" class="upload-box" prop="image">
								<div class="case-img-upload">
									<div class="case-img-upload-btns">
										<el-upload :disabled="disabled" ref="upload" action="fakeaction" :show-file-list="false" :http-request="function (res) { return upload(res,1)}">
											<el-button :disabled="disabled" type="primary" size="small">上传图片</el-button>
										</el-upload>
										<div class="el-upload__tip">小于500KB</div>
									</div>
									<div class="case-img-upload-imgs">
										<el-image :src="caseForm.image">
											<div slot="error"></div>
										</el-image>
									</div>
								</div>
							</el-form-item>
						</el-col>
						<el-col :span="18">
							<el-form-item label="上传附图:" class="upload-box" prop="vice_big">
								<div class="case-img-upload">
									<div class="case-img-upload-btns">
										<el-upload :disabled="disabled" ref="upload" action="fakeaction" :show-file-list="false" :http-request="function (res) { return upload(res,2)}"
										 multiple accept="image/*">
											<el-button :disabled="disabled" type="primary" size="small">上传图片</el-button>
										</el-upload>
										<el-button :disabled="disabled" type="danger" size="small" @click="rest('vice')">重置</el-button>
										<div class="el-upload__tip">小于500KB</div>
									</div>
									<div class="case-img-upload-imgs">
										<el-image v-if="!vice_big.length">
											<div slot="error"></div>
										</el-image>
										<div v-for="(data,index) in vice_big" :key="index" class="vice_big_box" v-else>
											<i class="el-icon-error" @click="delVice(index,1)"></i>
											<el-image :preview-src-list="vice_big_preview" :src="data.image" fit="contain"></el-image>
										</div>
									</div>
								</div>
							</el-form-item>
						</el-col>
						<el-col :span="24">
							<el-form-item label="上传视频:" class="upload-box">
								<div class="case-img-upload">
									<div class="case-img-upload-btns">
										<el-upload :disabled="disabled" ref="upload" action="fakeaction" :show-file-list="false" :http-request="function (res) { return uploadVideo(res,1)}"
										 accept="video/mp4,avi">
											<el-button :disabled="disabled" type="primary" size="small">上传视频</el-button>
										</el-upload>
										<el-button :disabled="disabled" type="danger" size="small" @click="rest('video')">重置</el-button>
										<div class="el-upload__tip">小于20MB</div>
									</div>
									<div class="case-img-upload-imgs">
										<el-image v-show="!caseForm.video">
											<div slot="error"></div>
										</el-image>
										<div class="vice_big_box" style="width: 500px; margin-left: 25px;" v-show="caseForm.video">
											<video-player :disabled="disabled" id="video" ref="videoPlayer" class="vjs-custom-skin" :playsinline="true"
											 :options="playerOptions" />
										</div>
									</div>
								</div>
							</el-form-item>
						</el-col>
						<el-col :span="14">
							<el-form-item label="案例详情:" prop="content">
								<div style="display: flex;justify-content: flex-end;">
									<el-switch v-model="phoneShow" active-text="开启预览" active-color="#009688"></el-switch>
								</div>
								<quill-editor class="ql-editor" ref="myQuillEditor" v-model="caseForm.content" :options="editorOption"></quill-editor>
							</el-form-item>
						</el-col>
					</div>
				</el-row>
				<el-button type="primary" @click="submitForm('caseForm')" style="margin-left: 40px;" v-if="!$route.query.id">添加</el-button>
				<el-button v-if="$route.query.id && $route.query.type!=1" type="primary" @click="submitForm('caseForm')" style="margin-left: 40px;">修改</el-button>
			</el-form>
		</el-card>


		<mobilePhone v-if="phoneShow" :content="caseForm.content"></mobilePhone>

	</div>
</template>

<script>
	import mobilePhone from './mobile-phone';
	import 'quill/dist/quill.core.css'; // import styles
	import 'quill/dist/quill.snow.css'; // for snow theme
	import 'quill/dist/quill.bubble.css'; // for bubble theme
	import {
		quillEditor,
		Quill
	} from 'vue-quill-editor';
	import {
		container,
		addQuillTitle
	} from 'quill-video-image-module';
	import {
		ImageExtend,
		QuillWatch
	} from 'quill-video-image-module';
	import {
		VideoExtend,
		QuillVideoWatch
	} from 'quill-video-image-module';

	// 引入video模块并注册
	import video from 'quill-video-image-module/video';
	Quill.register(video, true);

	Quill.register('modules/ImageExtend', ImageExtend);
	Quill.register('modules/VideoExtend', VideoExtend);

	import recommend from '@/components/layer-dialog/good-recommend.vue';
	import md5 from 'md5'
	export default {
		components: {
			recommend,
			quillEditor,
			mobilePhone
		},
		data() {
			return {
				phoneShow: false,
				disabled: false,
				type: '',
				admin_type: localStorage.getItem('admin_type'),
				admin_id: localStorage.getItem('admin_id'),
				upImage: {
					timestamp: Math.round(new Date() * 1000),
					key: localStorage.getItem('token'),
					port: 'pc',
				},
				mainUploadUrl: this.$ApiList.mainUpload.url,
				styleList: [],
				apace_list: [],
				vice_big: [],
				vice_middle: [],
				img_info: [],
				vice_big_preview: [],
				img_info_preview: [],
				goods_sn: '',
				caseForm: {
					content: '',
					sort: 0,
					case_name: '',
					style_id: '',
					square: '',
					space: '',
					goods_sn: this.goods_sn,
					brief: '',
					image: '',
					image_middle: '',
					image_thumb: '',
					vice_big: '',
					vice_middle: '',
					img_info: '',
					video: 0
				},
				playerOptions: {
					playbackRates: [0.7, 1.0, 1.5, 2.0], //播放速度
					autoplay: false, // 如果true,浏览器准备好时开始回放。
					preload: 'auto', // 建议浏览器在<video>加载元素后是否应该开始下载视频数据。auto浏览器选择最佳行为,立即开始加载视频（如果浏览器支持）
					language: 'zh-CN',
					aspectRatio: '16:9', // 将播放器置于流畅模式，并在计算播放器的动态大小时使用该值。值应该代表一个比例 - 用冒号分隔的两个数字（例如"16:9"或"4:3"）
					fluid: true, // 当true时，Video.js player将拥有流体大小。换句话说，它将按比例缩放以适应其容器。
					sources: [{
						type: 'video/mp4',
						src: ''
					}],
					hls: true,
					poster: '', // 你的封面地址
					width: '500px', // 播放器宽度
					notSupportedMessage: '此视频暂无法播放，请稍后再试'
				},
				// 需要对比的数据
				compared: {
					goods_sn: '',
					vice_big: '',
					vice_middle: '',
					img_info: ''
				},
				caseFormRules: {
					content: [{
						required: true,
						message: '请输入内容'
					}],
					sort: [{
						required: true,
						message: '请输入序号'
					}],
					case_name: [{
						required: true,
						message: '请输入案例名称',
						tigger: 'blur'
					}],
					style_id: [{
						required: true,
						message: '请选择风格',
						tigger: 'change'
					}],
					square: [{
						required: true,
						message: '请输入平方数',
						tigger: 'blur'
					}],
					space: [{
						required: true,
						message: '请输入空间类型',
						tigger: 'blur'
					}],
					image: [{
						required: true,
						message: '请上传主图'
					}],
					vice_big: [{
						required: true,
						message: '请上传至少一张附图'
					}]
				},
				// 富文本框参数设置
				editorOption: {
					modules: {
						ImageExtend: {
							loading: true, // 可选参数 是否显示上传进度和提示语
							name: 'file[]', // 图片参数名
							size: 1, // 可选参数 图片大小，单位为M，1M = 1024kb
							action: `${this.$domain}api/Upimg/UpImg`, // 服务器地址, 如果action为空，则采用base64插入图片
							// response 为一个函数用来获取服务器返回的具体图片地址
							// 例如服务器返回{code: 200; data:{ url: 'baidu.com'}}
							// 则 return res.data.url
							response: res => {
								return res.datas[0];
							},
							headers: () => {}, // 可选参数 设置请求头部
							start: () => {}, // 可选参数 自定义开始上传触发事件
							end: () => {}, // 可选参数 自定义上传结束触发的事件，无论成功或者失败
							error: () => {}, // 可选参数 自定义网络错误触发的事件
							change: (xhr, formData) => {
								formData.append('timestamp', Math.round(new Date() * 1000));
								formData.append('port', 'pc');
								formData.append('sign', this.getSign());
								formData.append('key', localStorage.getItem('token'));
							}, // 可选参数 每次选择图片触发，也可用来设置头部，但比headers多了一个参数，可设置formData
							sizeError: () => {
								this.$message({
									message: '图片不能大于1M',
									type: 'warning'
								});
							}
						},
						VideoExtend: {
							loading: true,
							name: 'file[]',
							size: 100, // 可选参数 视频大小，单位为M，1M = 1024kb
							action: `${this.$domain}api/Upimg/UpVideo`, // 视频上传接口
							headers: xhr => {
								// set custom token(optional)
							},
							response: res => {
								// video uploaded path
								// custom your own
								return res.datas;
							},
							change: (xhr, formData) => {
								formData.append('timestamp', Math.round(new Date() * 1000));
								formData.append('port', 'pc');
								formData.append('sign', this.getSign());
								formData.append('key', localStorage.getItem('token'));
							}, // 可选参数 每次选择图片触发，也可用来设置头部，但比headers多了一个参数，可设置formData
							sizeError: () => {
								this.$message({
									message: '视频不能大于100M',
									type: 'warning'
								});
							}
						},
						toolbar: {
							container: container, // container为工具栏，此次引入了全部工具栏，也可自行配置
							handlers: {
								image: function() {
									// 劫持原来的图片点击按钮事件
									QuillWatch.emit(this.quill.id);
								},
								video: function() {
									QuillVideoWatch.emit(this.quill.id);
								}
							}
						}
					}
				}
			}
		},
		methods: {
			init() {
				this.type = this.$route.query.type
				// type 0编辑 1 详情
				if (this.type == 1) {
					this.disabled = true;
				}
				let data = {
					case_id: this.$route.query.id
				};
				this.$http(this.$ApiList.caseInfo, data).then(res => {

					this.styleList = res.datas.style_list
					this.apace_list = res.datas.apace_list
					if (res.datas.list.case_id) {
						this.playerOptions.poster = res.datas.list.image
						// 界面详情图
						this.img_info = res.datas.list.img_info
						// 弹窗详情图
						this.img_info.forEach(item => {
							this.img_info_preview.push(item.image)
						})
						this.vice_big = res.datas.list.vice_big
						// 弹窗附图
						this.vice_big.forEach(item => {
							this.vice_big_preview.push(item.image)
						})
						// 附图
						this.vice_middle = res.datas.list.vice_middle
						// 保存字段对比
						let vice_big = [],
							vice_middle = [],
							img_info = []

						res.datas.list.vice_big.forEach(item => {
							vice_big.push(item.image)
						})
						res.datas.list.vice_middle.forEach(item => {
							vice_middle.push(item.image)
						})
						res.datas.list.img_info.forEach(item => {
							img_info.push(item.image)
						})

						this.compared = {
							goods_sn: res.datas.list.goods_sn,
							vice_big: vice_big.join(','),
							vice_middle: vice_middle.join(','),
							img_info: img_info.join(',')
						}

						this.goods_sn = res.datas.list.goods_sn
						this.caseForm = {
							sort: res.datas.list.sort,
							case_name: res.datas.list.case_name,
							style_id: res.datas.list.style_id.toString(),
							square: res.datas.list.square.toString(),
							space: res.datas.list.space,
							goods_sn: res.datas.list.goods_sn,
							brief: res.datas.list.brief,
							image: res.datas.list.image,
							image_middle: res.datas.list.image_middle,
							image_thumb: res.datas.list.image_thumb,
							vice_big: res.datas.list.vice_big,
							vice_middle: res.datas.list.vice_middle,
							img_info: res.datas.list.img_info,
							content: res.datas.list.content,
							video: res.datas.list.video != 0 ? res.datas.list.video : ''
						}

						if (res.datas.list.content == null) {
							this.caseForm.content = '<p></p>'
							res.datas.list.img_info.forEach((item) => {
								this.caseForm.content += '<p><img src="' + item.image + '"></p>'
							})
						}
						this.playerOptions.sources[0].src = res.datas.list.video != 0 ? res.datas.list.video : ''
					}
				})
			},
			// 图片上传
			upload(params, type) {
				const file = params.file,
					fileType = file.type,
					isJPGPNG = file.type === 'image/jpeg' || 'image/png',
					isLt500KB = file.size / 1024 <= 500;
				if (!isJPGPNG) {
					this.$message.error("只能上传图片格式png、jpg!");
					return;
				}
				if (!isLt500KB) {
					this.$message.error("图片不能大于500K!");
					return;
				}
				const form = new FormData();
				form.append("file[]", file);
				switch (Number(type)) {
					case 1:
						this.$http(this.$ApiList.mainUpload, form).then(res => {
							this.caseForm.image = res.datas[0].major_img_big
							this.caseForm.image_middle = res.datas[0].major_img_middle
							this.caseForm.image_thumb = res.datas[0].major_img_thumb
						})
						break;
					case 2:
						if (this.$route.query.id) {
							form.append('type', 1)
							form.append('case_id', this.$route.query.id)
							this.$http(this.$ApiList.AddCaseImg, form).then(res => {
								this.vice_big_preview.push(res.datas[0].imgUrl)
								this.vice_big.push({
									image: res.datas[0].imgUrl,
									case_image_id: res.datas[0].image_id
								})
								this.vice_middle.push({
									image: res.datas[0].imgUrl,
									case_image_id: res.datas[0].image_id
								})
							})
						} else {
							let index = 0
							this.$http(this.$ApiList.viceUpload, form).then(res => {
								this.vice_big_preview.push(res.datas[0].vice_img_big)
								this.vice_big.push({
									image: res.datas[0].vice_img_big,
									case_image_id: index++
								})
								this.vice_middle.push({
									image: res.datas[0].vice_img_middle,
									case_image_id: index++
								})
							})
						}
						break;
				}
			},
			// 视频上传
			uploadVideo(params, type) {
				const file = params.file,
					isLt20MB = file.size / 1024 / 1024 < 20;
				if (!isLt20MB) {
					this.$message.error("视频不能大于20MB！");
					return;
				}
				const form = new FormData();
				form.append("file[]", file);
				this.$http(this.$ApiList.UpVideo, form).then(res => {
					this.caseForm.video = res.datas
					this.$nextTick(() => {
						this.playerOptions.sources[0].src = res.datas
					})
				})
			},
			// 重置图片
			rest(type) {
				switch (type) {
					case 'vice':
						this.vice_big = []
						this.vice_middle = []
						break;
					case 'infoImg':
						this.img_info = []
						this.img_info_preview = []

						break;
				}
			},
			// 删除附图
			delVice(index, type) {
				if (this.type == 1) {
					return
				}
				this.$confirm('删除后不可恢复，是否确认删除?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					let id = ''
					if (type == 1) {
						id = this.vice_big[index].case_image_id
					} else {
						if (this.$route.query.id == undefined) {
							this.img_info.splice(index, 1)
							return
						} else {
							id = this.img_info[index].case_image_id
						}
					}
					let data = {
						case_image_id: id
					}
					this.$http(this.$ApiList.DelCaseImg, data).then(res => {
						if (type == 1) {
							this.vice_big.splice(index, 1)
							this.vice_middle.splice(index, 1)
						} else {
							this.img_info.splice(index, 1)
						}
					})
				}).catch(() => {

				});
			},
			//提交
			submitForm(formName) {
				let img_info = [],
					vice_middle = [],
					vice_big = []
				this.img_info.forEach(item => {
					img_info.push(item.image)
				})
				this.vice_big.forEach(item => {
					vice_big.push(item.image)
				})
				this.vice_middle.forEach(item => {
					vice_middle.push(item.image)
				})
				this.caseForm.img_info = img_info.join(',')
				this.caseForm.vice_big = vice_big.join(',')
				this.caseForm.vice_middle = vice_middle.join(',')
				this.$refs[formName].validate((valid) => {
					if (valid) {
						if (!this.$route.query.id) {
							// this.$layer.msg('暂停开放案例上传功能')
							// return
							if (this.admin_id == 3) {
								this.caseForm.type = 3 // 1平台上传 2商家上传 3 工厂上传
								this.caseForm.factory_id = localStorage.getItem('factory_id')
							}
							if (this.admin_id == 2) {
								this.caseForm.type = 2 // 1平台上传 2商家上传 3 工厂上传
							}
							if (this.admin_type == 1) {
								this.caseForm.type = 1 // 1平台上传 2商家上传 3 工厂上传
							}
							this.$http(this.$ApiList.caseAdd, this.caseForm).then(res => {
								this.$layer.msg('案例上传成功')
								setTimeout(() => {
									this.$router.push({
										path: '/case_list'
									})
								}, 1500)
							})
						} else {

							// 商品编号，附图，详情图判断如果没有修改就不用传
							if (this.compared.goods_sn == this.goods_sn) {
								delete this.caseForm.goods_sn
							} else {
								this.caseForm.goods_sn = this.goods_sn
							}
							if (this.compared.vice_big == this.caseForm.vice_big) {
								delete this.caseForm.vice_big
							}
							if (this.compared.vice_middle == this.caseForm.vice_middle) {
								delete this.caseForm.vice_middle
							}
							if (this.compared.img_info == this.caseForm.img_info) {
								delete this.caseForm.img_info
							}
							this.caseForm.case_id = this.$route.query.id

							if (this.admin_id == 3) {
								this.caseForm.type = 3 // 1平台上传 2商家上传 3 工厂上传
								this.caseForm.factory_id = localStorage.getItem('factory_id')
							}
							if (this.admin_id == 2) {
								this.caseForm.type = 2 // 1平台上传 2商家上传 3 工厂上传
							}
							if (this.admin_id == 1) {
								this.caseForm.type = 1 // 1平台上传 2商家上传 3 工厂上传
							}
							this.$http(this.$ApiList.caseAdd, this.caseForm).then(res => {
								this.$layer.msg('案例修改成功')
								setTimeout(() => {
									this.$router.push({
										path: '/case_list'
									})
								}, 1500)
							})
						}
					} else {
						this.$layer.msg('请填写完整信息后提交')
					}
				});
			},
			upSuccess(response, file, fileList) {
				this.img_info_preview.push(file.response.datas[0]);
				this.img_info.push({
					image: file.response.datas[0]
				});
				console.log('img_info', this.img_info)
				console.log('img_info_preview', this.img_info_preview)
			},
			getSign() {
				let data = this.upImage
				// 获取签名开始
				let obj = 'jjds2020+'
				let newObj = this.objKeySort(data)
				for (let i in newObj) {
					obj += i + '=' + newObj[i] + '&'
				}
				obj = obj.substring(0, obj.length - 1)
				obj += '+jjds2020'
				obj = md5(obj)
				obj = obj.toUpperCase()
				// 获取签名结束
				this.upImage.sign = obj
			},
			// 参数排序
			objKeySort(obj) {
				var newkey = Object.keys(obj).sort();
				var newObj = {};
				for (var i = 0; i < newkey.length; i++) {
					newObj[newkey[i]] = obj[newkey[i]];
				}
				return newObj;
			},
			openGoodsView() {
				this.$layer.iframe({
					title: '选择商品',
					maxmin: true,
					area: ['50%', '60%'],
					content: {
						content: recommend, //传递的组件对象
						parent: this, //当前的vue对象
						data: {

						} //props
					}
				});
			},
			unique(arr) {
				return Array.from(new Set(arr))
			},
			setGoodsId(ids) {
				if (this.goods_sn == '') {
					this.goods_sn = ids
				} else {
					this.goods_sn = this.goods_sn + ',' + ids
					let arr = this.goods_sn.split(',');
					let newArr = this.unique(arr)
					this.goods_sn = newArr.join(',')
				}
			}
		},
		created() {
			this.$nextTick(() => {
				this.init()
				this.getSign()
			})
		},
		mounted() {
			addQuillTitle();
		}
	}
</script>
<style lang="scss">
	.case_data {
		.last {
			margin-bottom: 0;
		}

		.upload-drag {
			.el-upload {
				vertical-align: top;
			}

			.el-upload__tip {
				line-height: normal;
			}
		}

		.case_upload {
			display: flex;
			flex-wrap: wrap;

			.el-col {}
		}

		.el-select {
			display: block;
		}

		.upload-box {
			padding-left: 40px;

			.case-img-upload {
				display: flex;

				.case-img-upload-imgs {
					flex: 1;
					align-items: flex-start;

					.el-image {
						width: 140px;
						height: 140px;
						border: solid 1px #E5E5E5;
						margin-left: 25px;
						vertical-align: top;
					}
				}

				.case-img-upload-imgs-info {
					width: 100%;
					max-width: 660px;
					border: solid 1px #E5E5E5;
					margin-left: 25px;
					min-height: 390px;

					.case-img-upload-imgs-info-box {
						position: relative;

						.el-icon-error {
							position: absolute;
							font-size: 20px;
							color: #ef3030;
							right: 5px;
							top: 5px;
							z-index: 1;
							background-color: #FFF;
							border-radius: 50%;
							cursor: pointer;
						}
					}

					.el-image {
						width: 100%;
						vertical-align: top;
					}
				}

				.vice_big_box {
					position: relative;
					display: inline-block;
					vertical-align: top;
					margin-bottom: 20px;

					.el-icon-error {
						position: absolute;
						font-size: 20px;
						color: #ef3030;
						right: 5px;
						top: 5px;
						z-index: 1;
						background-color: #FFF;
						border-radius: 50%;
						cursor: pointer;
					}
				}
			}

			.el-upload__tip {
				width: 80px;
				text-align: center;
			}

			.el-form-item__label {
				float: none;
			}

			.el-form-item__content {
				margin-left: 0 !important;

				.el-button--danger {
					width: 80px;
					background-color: #37C1D6;
					border-color: #37C1D6;
				}
			}
		}

		.ql-editor {
			min-height: 500px;
		}

		/* 解决粘贴后光标会自动弹到文档的初始位置 */
		.ql-clipboard {
			position: fixed;
			display: none;
			left: 50%;
			top: 50%;
		}
	}
</style>
